import 'dart:math';

import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:jet_rails/jr_app/jr_models/jr_article_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_comment_model.dart';
import 'package:jet_rails/jr_app/jr_views/jr_discovery/jr_discovery_controller.dart';
import 'package:jet_rails/jr_app/jr_views/jr_discovery/jr_voice_input_controller.dart';
import 'package:jet_rails/jr_app/jr_views/jr_discovery/jr_voice_input_view.dart';
import 'package:jet_rails/jr_app/jr_views/jr_user/jr_user_controller.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_app_bar.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_blur_container.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_buttons.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_comment_widget.dart';
import 'package:jet_rails/jr_app/jr_widgets/jr_scaffold.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_snippet.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';
import 'package:jet_rails/jr_utils/jr_translation.dart';

class JrArticleDetailView extends StatefulWidget {
  const JrArticleDetailView({
    super.key,
    required this.articleModel,
  });

  final JrArticleModel articleModel;

  @override
  State<JrArticleDetailView> createState() => _JrArticleDetailViewState();
}

class _JrArticleDetailViewState extends State<JrArticleDetailView> {
  JrDiscoveryController controller = Get.find<JrDiscoveryController>();
  final TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();
    checkAutoTranslate();
    Get.put(JrVoiceInputController(articleModel: widget.articleModel));
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    Get.delete<JrVoiceInputController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: JrScaffold(
        defaultTopPadding: false,
        appBar: JrAppBar(
          title: '',
          backgroundColor: Colors.transparent,
          showRailIcon: false,
          actions: [
            if (!JrServices.instance.isMe(widget.articleModel.author?.userId ?? ''))
              Container(
                height: 30.h,
                margin: EdgeInsets.only(right: 20.w, top: 7.h, bottom: 7.h),
                child: GestureDetector(
                  onTap: () {
                    if (widget.articleModel.author?.userId != null) {
                      JrSnippets.popMoreMenuDialog(widget.articleModel.author!.userId);
                    }
                  },
                  child: Image.asset(
                    'assets/webp/icon_more_option_action.webp',
                    height: 36.h,
                  ),
                ),
              )
          ],
        ),
        body: Stack(
          clipBehavior: Clip.none,
          children: [
            Positioned(top: 0, left: 0, right: 0, height: 280.h, child: buildPoster()),
            Positioned(bottom: 0, left: 0, right: 0, height: 565.h, child: buildContentPanel()),
            Positioned(bottom: 0, left: 0, right: 0, height: 90.h, child: buildInputWidget()),
            Positioned.fill(child: buildVoiceInputModal()),
          ],
        ),
      ),
    );
  }

  Widget buildPoster() {
    final allContent = List.from(widget.articleModel.content)..insert(0, widget.articleModel.thumbnail);
    return SizedBox(
      height: 280.h,
      child: Swiper(
        loop: false,
        itemCount: allContent.length,
        itemBuilder: (BuildContext context, int index) {
          if (allContent.isNotEmpty) {
            return Image.asset(
              allContent.elementAt(index),
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover,
            );
          }
          return Container();
        },
      ),
    );
  }

  Widget buildContentPanel() {
    return JrBlurContainer(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(topLeft: const Radius.circular(24), topRight: Radius.circular(24.r)),
          gradient: const LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Color.fromRGBO(164, 110, 255, 0.6), Color.fromRGBO(164, 110, 255, 0.2)],
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            buildInfoWidget(),
            Expanded(
                child: SingleChildScrollView(
              child: Column(children: [
                Container(
                  height: 16.h,
                ),
                buildCommentsWidget(),
                SizedBox(height: 90.h),
              ]),
            ))
          ],
        ));
  }

  Widget buildInfoWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.articleModel.title,
          style: TextStyle(color: Colors.white, fontSize: 16.sp),
        ),
        SizedBox(height: 16.h),
        Text(
          '${controller.translatedArticle.isEmpty ? widget.articleModel.description : controller.translatedArticle}',
          style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 14.sp),
        ),
        SizedBox(height: 16.h),
        Row(
          children: [
            if (widget.articleModel.author?.avatar != null)
              CircleAvatar(
                radius: 16.r,
                backgroundImage: NetworkImage(widget.articleModel.author?.avatar ?? ''),
              ),
            SizedBox(width: 10.w),
            Expanded(
                child: Row(
              children: [
                if (widget.articleModel.author?.nickname != null)
                  Flexible(
                      child: Text(
                    widget.articleModel.author?.nickname ?? '',
                    style: TextStyle(fontSize: 14.sp, color: Colors.white),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  )),
                SizedBox(width: 8.w),
                Obx(() {
                  String userId = widget.articleModel.author?.getId ?? '';
                  bool followed = JrServices.instance.isFollowed(widget.articleModel.author?.userId ?? '');
                  return JrGradientButton(
                    height: 16.h,
                    width: 55.w,
                    textStyle: const TextStyle(color: Colors.white, fontSize: 11),
                    text: followed ? 'unfollow' : 'follow',
                    onTap: () async {
                      try {
                        EasyLoading.show();
                        if (followed) {
                          await JrServices.instance.unFollow(userId);
                          JrToast.show('Unfollow Successfully');
                        } else {
                          await JrServices.instance.follow(userId);
                          JrToast.show('Follow Successfully');
                        }
                      } catch (e, s) {
                        JrLogger.e('$e  $s');
                      } finally {
                        EasyLoading.dismiss();
                      }
                    },
                  );
                }),
              ],
            )),
            SizedBox(width: 8.w),
            GestureDetector(
              onTap: translateDescription,
              child: Image.asset('assets/webp/icon_translate.webp', width: 28.w, height: 28.h),
            ),
            SizedBox(width: 24.w),
            StatefulBuilder(
              builder: (context, setState) => GestureDetector(
                onTap: () {
                  controller.toggleLikeStatus(widget.articleModel);
                },
                child: Image.asset(
                  widget.articleModel.likedByMe ?? false
                      ? 'assets/webp/icon_like_active.webp'
                      : 'assets/webp/icon_like_default.webp',
                  width: 28.r,
                  height: 28.r,
                ),
              ),
            )
          ],
        ),
      ],
    );
  }

  Widget buildCommentsWidget() {
    //#A46EFF
    return StatefulBuilder(
      builder: (context, setState) => Obx((){
        final commentLength = JrServices.instance.allArticle[0].commentList.length;
        return Column(
            children: widget.articleModel.commentList
                .map((comment) => JrCommentWidget(
                      commentModel: comment,
                      action: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          if (comment.likedByMe == true) {
                            comment.likedByMe = false;
                          } else {
                            comment.likedByMe = true;
                          }
                          JrServices.instance.saveArticle();
                          setState(() {});
                        },
                        child: Container(
                          padding: EdgeInsets.only(left: 7.w, top: 4.h, bottom: 4.h),
                          child: Image.asset(
                              comment.likedByMe ?? false
                                  ? 'assets/webp/icon_like_active.webp'
                                  : 'assets/webp/icon_like_default.webp',
                              height: 30.h),
                        ),
                      ),
                    ))
                .toList(),
          );
      }),
    );
  }

  Widget buildInputWidget() {
    return Container(
      height: 90.h,
      decoration: BoxDecoration(
        color: Colors.white30,
        borderRadius: const BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)),
        boxShadow: [BoxShadow(color: Colors.grey.withOpacity(0.5), blurRadius: 10)],
      ),
      child: Row(
        children: [
          SizedBox(width: 20.w),
          Obx(() => GestureDetector(
                onTap: () {
                  Get.find<JrVoiceInputController>().toggleVoiceInput();
                },
                child: Image.asset(
                  Get.find<JrVoiceInputController>().isVoiceInput.value
                      ? 'assets/webp/icon_keyboard.webp'
                      : 'assets/webp/icon_voice_input.webp',
                  width: 28.w,
                  height: 28.h,
                ),
              )),
          SizedBox(width: 20.w),
          Expanded(
            child: Obx(() => Get.find<JrVoiceInputController>().isVoiceInput.value
                ? buildVoiceInputWidget()
                : buildTextInputWidget()),
          ),
          SizedBox(width: 20.w),
          GestureDetector(
            onTap: () {
              onClickSendBtn();
            },
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.w),
                color: const Color(0xFF404040),
              ),
              width: 62.w,
              height: 32.h,
              child: Text(
                'Send',
                style: TextStyle(color: Colors.white, fontSize: 16.sp),
              ),
            ),
          ),
          SizedBox(width: 20.w),
        ],
      ),
    );
  }

  Widget buildTextInputWidget() {
    return Container(
      height: 44.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: const Color(0x99FFFFFF),
        borderRadius: BorderRadius.circular(36.w),
      ),
      child: TextField(
        controller: _textEditingController,
        onSubmitted: (value) {
          onClickSendBtn();
        },
        decoration: const InputDecoration(
          hintStyle: TextStyle(height: 1),
          hintText: 'Enter your ideas...',
          border: InputBorder.none,
          contentPadding: EdgeInsets.only(left: 20, right: 20, top: 5, bottom: 5),
        ),
        maxLines: 1,
      ),
    );
  }

  Widget buildVoiceInputWidget() {
    return const JrVoiceInputWidget();
  }

  Widget buildVoiceInputModal() {
    return IgnorePointer(
      child: Obx(() {
        return Get.find<JrVoiceInputController>().isRecording.value ? const RecordStatusView() : Container();
      }),
    );
  }

  void checkAutoTranslate() {
    bool autoTranslation = Get.find<JrUserController>().autoTranslation.value;
    if (autoTranslation) {
      translateDescription();
    }
  }

  Future<void> translateDescription() async {
    String? txt = await JrTranslate.translate(widget.articleModel.description);
    if (txt != null) {
      controller.translatedArticle.value = txt;
      controller.translatedArticle.refresh();
    } else {
      JrToast.show('translate failed');
    }
  }

  void onClickSendBtn() async {
    try {
      FocusScope.of(context).unfocus();
      EasyLoading.show();
      await Future.delayed(Duration(milliseconds: 1000 + Random().nextInt(1000)));
      String content = _textEditingController.text;
      JrCommentModel comment = JrCommentModel(
        avatar: JrServices.instance.loginUser.value.getAvatarUrl,
        nickname: JrServices.instance.loginUser.value.nickname,
        content: content,
      );
      widget.articleModel.commentList.insert(0, comment);
      setState(() {});
      await JrServices.instance.saveActivity();
      await controller.refreshArticleList();
      _textEditingController.text = '';
    } finally {
      EasyLoading.dismiss();
    }
  }
}
